package com.hqd.ch03.v28.factory.support;

import com.hqd.ch03.v28.beans.Mergeable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ManagedList<E> extends ArrayList<E> implements Mergeable {
    private String elementTypeName;

    private boolean mergeEnabled;


    public ManagedList() {
    }

    public ManagedList(int initialCapacity) {
        super(initialCapacity);
    }

    @SafeVarargs
    public static <E> ManagedList<E> of(E... elements) {
        ManagedList<E> list = new ManagedList<>();
        Collections.addAll(list, elements);
        return list;
    }

    public String getElementTypeName() {
        return this.elementTypeName;
    }

    public void setElementTypeName(String elementTypeName) {
        this.elementTypeName = elementTypeName;
    }

    @Override
    public boolean isMergeEnabled() {
        return this.mergeEnabled;
    }

    public void setMergeEnabled(boolean mergeEnabled) {
        this.mergeEnabled = mergeEnabled;
    }

    @Override
    public List<E> merge(Object parent) {
        if (!this.mergeEnabled) {
            throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'");
        }
        if (parent == null) {
            return this;
        }
        if (!(parent instanceof List)) {
            throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]");
        }
        List<E> merged = new ManagedList<>();
        merged.addAll((List<E>) parent);
        merged.addAll(this);
        return merged;
    }
}
